<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax接收JSON格式数据</title>

    <style>
        div {
            width: 100px;
            height: 50px;
            border: solid 2px green;
        }
    </style>
</head>

<body>
    用户名：
    <div id="username"></div>
    年龄：
    <div id="age"></div>
    住址：
    <div id="city"></div>

    <script>
        const username = document.getElementById('username');
        const age = document.getElementById('age');
        const city = document.getElementById('city');

        // 监听按键按下事件
        window.onkeydown = function() {
            const xhr = new XMLHttpRequest();
            xhr.open('get', 'http://127.0.0.1:9999/json-server');

            // 设置ajax响应格式为JSON，这样就不需要我们手动解析
            xhr.responseType = 'json';

            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 手动解析JSON数据
                        // const user = JSON.parse(xhr.response);
                        // username.innerHTML = user.username;
                        // age.innerHTML = user.age;
                        // city.innerHTML = user.city;

                        username.innerHTML = xhr.response.username;
                        age.innerHTML = xhr.response.age;
                        city.innerHTML = xhr.response.city;
                    }
                }
            }
        }
    </script>
</body>

</html>